<!-- 分享首页 -->
<template>
  <view class="share_layout_box">
    <canvas class="myCanvas test" :style="'width:'+myCanvasWidth+'px;height:'+myCanvasHeight+'px'" canvas-id="sharePosterFrendsId"></canvas>
  </view>
</template>
<script>
// let canvasData = {
//   bgImgUrl: 'https://image.qqpyyds.com/uni_app/user/163549354120386.png', // 封面大图片
//   page: '/pages/index/index', // 二维码地址
//   userAvatar: 'https://image.qqpyyds.com/user/avatar/1448144136114941954', // 用户头像
//   userNickname: '廖志林',  // 用户昵称
//   helpSellExplainList: [
//     {label:"急款",showType:true,id:1},
//     {label:"独家资源",showType:true,id:5},
//     {label:"24小时售后",showType:true,id:2}
//   ],
//   fansMun: '1.2w', // 粉丝数
//   fansText: '粉丝数', // 粉丝数
//   videosMun: '332', // 视频数
//   videosText: '视频数', // 视频数
//   watchMun: '3345w', // 观看人次
//   watchText: '观看人次', // 观看人次
//   codeText1: '长按识别关注，随时获取我的最新动态', // 二维码提示文案1
//   codeText2: ' TA的视频都在这里，太精彩了。', // 二维码提示文案2
// }
// this.$refs.childQueryLogisticsShare.sharePosterFrends(canvasData)
// import { writeFile, removeSave } from '@/api/baseConvert'
import share from "@/api/share.js"
export default {
  data () {
    return {
      myCanvasWidth: 280,
      myCanvasHeight: 504,
      dpiMun: 3,
    }
  },
  created () {
    this.myCanvasWidth = this.myCanvasWidth*this.dpiMun
    this.myCanvasHeight = this.myCanvasHeight*this.dpiMun
  },
  methods: {
    async sharePosterFrends(data) {
      wx.showLoading({
        title: '生成中...',
        mask: true
      })
      let _this = this
      let _data = data
      let paramMap = {
        page: _data?.page ?? 'pages/index/index',
        ..._data.options
      }
      share.getSunCode(paramMap).then(async (res_) => {
        if (res_.code == 200) {
          let pam = {
            ..._data,
            QRCode: res_.data
          }
          await _this.createdCode(pam)
          let shareData = {}
          wx.canvasToTempFilePath({
            canvasId: 'sharePosterFrendsId',
            fileType: 'jpg',
            width: _this.myCanvasWidth,
            height: _this.myCanvasHeight,
            destWidth: _this.myCanvasWidth * 2,
            destHeight: _this.myCanvasHeight * 2,
            success: async (res) => {
              shareData = {
                code: '200',
                msg: '绘制成功！',
                url: res.tempFilePath
              }
              console.log(shareData,'绘制成功')
              // _this.$store.commit('POSTER_SHARING_DATA', shareData)
              _this.$emit('posterShareSuccess', shareData)
              wx.hideLoading()
            },
            fail: function (res) {
              wx.hideLoading()
              console.log('绘制失败')
            }
          },_this)
          // removeSave() // 先删除在添加
          // writeFile(res_.data).then(async (img)=>{
          // }).catch(e=>{
          //   wx.hideLoading()
          //   console.log(e)
          // })
        }
      })
    },
    // 开始绘图
    createdCode (data) {
      const _this = this
      let fromData = data
      return new Promise(resolve => {
        exec()
        async function exec () {
          const ctx = wx.createCanvasContext('sharePosterFrendsId', _this) // 绘图上下文
          ctx.setFillStyle('#fff')
          ctx.fillRect(0, 0, _this.myCanvasWidth, _this.myCanvasHeight)
          ctx.save()
          let bgImgUrl = fromData.bgImgUrl
          bgImgUrl = bgImgUrl+`?x-oss-process=image/resize,w_${_this.myCanvasWidth},h_${168*_this.dpiMun},m_fill/auto-orient,1/quality,q_90/format,jpg`
          await _this.drawImg(bgImgUrl, ctx, 0, 0, _this.myCanvasWidth, 168*_this.dpiMun)
          ctx.restore()
          ctx.save()
          ctx.beginPath()
          ctx.strokeStyle = '#fff'
          ctx.arc(40*_this.dpiMun,178*_this.dpiMun,28*_this.dpiMun,0,2*Math.PI)
          ctx.fill()
          ctx.clip()
          await _this.drawImg(fromData.userAvatar, ctx, 13*_this.dpiMun, 150*_this.dpiMun, 56*_this.dpiMun, 56*_this.dpiMun)
          ctx.restore()
          ctx.setFontSize(16*_this.dpiMun)
          ctx.setFillStyle('#323233')
          let userNickname = fromData.userNickname
          ctx.fillText(userNickname, 84*_this.dpiMun, 194*_this.dpiMun, 200*_this.dpiMun)
          ctx.restore()
          if (fromData.helpSellExplainList&&fromData.helpSellExplainList.length>0) {
            fromData.helpSellExplainList.forEach((item,i)=>{
              let Xmun = 32*_this.dpiMun
              if (i==1) {
                Xmun = Xmun + 16*_this.dpiMun + 12*_this.dpiMun
                Xmun = Xmun + ctx.measureText(fromData.helpSellExplainList[0].label).width
              }
              if (i==2) {
                Xmun = Xmun + 16*_this.dpiMun + 16*_this.dpiMun + 24*_this.dpiMun
                Xmun = Xmun + ctx.measureText(fromData.helpSellExplainList[0].label).width + ctx.measureText(fromData.helpSellExplainList[1].label).width
              }
              _this.handleBorderRect(ctx, Xmun, 222*_this.dpiMun, ctx.measureText(item.label).width+(16*_this.dpiMun), 20*_this.dpiMun, 4*_this.dpiMun, '#FFE5DE')
              ctx.setFontSize(10*_this.dpiMun)
              ctx.setFillStyle('#E44435')
              ctx.fillText(item.label, Xmun+(8*_this.dpiMun), 236*_this.dpiMun, 80*_this.dpiMun)
              ctx.restore()
              ctx.save()
            })
          }
          let multiple = 6
          let coordinateX = _this.myCanvasWidth/multiple
          let halfW = _this.myCanvasWidth/2
          let hMun1 = 280*_this.dpiMun
          let hMun2 = 300*_this.dpiMun
          ctx.setFontSize(16*_this.dpiMun)
          ctx.setFillStyle('#323232')
          ctx.fillText(fromData.fansMun, coordinateX-(ctx.measureText(fromData.fansMun).width/2), hMun1, halfW)
          ctx.setFontSize(12*_this.dpiMun)
          ctx.setFillStyle('#969799')
          ctx.fillText(fromData.fansText, coordinateX-(ctx.measureText(fromData.fansText).width/2), hMun2, halfW)
          if (fromData.videosMun) {
            ctx.setFontSize(16*_this.dpiMun)
            ctx.setFillStyle('#323232')
            ctx.fillText(fromData.videosMun, coordinateX-(ctx.measureText(fromData.videosMun).width/2)+(_this.myCanvasWidth/3), hMun1, halfW)
            ctx.setFontSize(12*_this.dpiMun)
            ctx.setFillStyle('#969799')
            ctx.fillText(fromData.videosText, coordinateX-(ctx.measureText(fromData.videosText).width/2)+(_this.myCanvasWidth/3), hMun2, halfW)
          }
          if (fromData.highQualityMun || fromData.highQualityMun === 0) {
            ctx.setFontSize(16*_this.dpiMun)
            ctx.setFillStyle('#323232')
            ctx.fillText(fromData.highQualityMun, coordinateX-(ctx.measureText(fromData.highQualityMun).width/2)+(_this.myCanvasWidth/3), hMun1, halfW)
            ctx.setFontSize(12*_this.dpiMun)
            ctx.setFillStyle('#969799')
            ctx.fillText(fromData.highQualityText, coordinateX-(ctx.measureText(fromData.highQualityText).width/2)+(_this.myCanvasWidth/3), hMun2, halfW)
          }
          ctx.setFontSize(16*_this.dpiMun)
          ctx.setFillStyle('#323232')
          ctx.fillText(fromData.watchMun, coordinateX-(ctx.measureText(fromData.watchMun).width/2)+(_this.myCanvasWidth/3*2), hMun1, halfW)
          ctx.setFontSize(12*_this.dpiMun)
          ctx.setFillStyle('#969799')
          ctx.fillText(fromData.watchText, coordinateX-(ctx.measureText(fromData.watchText).width/2)+(_this.myCanvasWidth/3*2), hMun2, halfW)
          ctx.restore()
          await _this.drawImg(fromData.QRCode, ctx, _this.myCanvasWidth/2-(40*_this.dpiMun), _this.myCanvasHeight-(150*_this.dpiMun), 80*_this.dpiMun, 80*_this.dpiMun)
          ctx.restore()
          ctx.setFontSize(12*_this.dpiMun)
          ctx.setFillStyle('#969799')
          ctx.fillText(fromData.codeText1, (_this.myCanvasWidth-ctx.measureText(fromData.codeText1).width)/2, _this.myCanvasHeight-(36*_this.dpiMun), _this.myCanvasWidth-(20*_this.dpiMun))
          if (fromData.codeText2) {
            ctx.setFontSize(12*_this.dpiMun)
            ctx.setFillStyle('#969799')
            ctx.fillText(fromData.codeText2, (_this.myCanvasWidth-ctx.measureText(fromData.codeText2).width)/2, _this.myCanvasHeight-(18*_this.dpiMun), _this.myCanvasWidth-(20*_this.dpiMun))
          }
          ctx.restore()
          ctx.draw(false, () => {
            resolve()
          })
        }
      })
    },
    // 画4个圆角
    handleBorderRect (ctx, x, y, w, h, r, color) {
      ctx.beginPath()
      // 左上角
      ctx.arc(x + r, y + r, r, Math.PI, 1.5 * Math.PI)
      ctx.moveTo(x + r, y)
      ctx.lineTo(x + w - r, y)
      ctx.lineTo(x + w, y + r)
      // 右上角
      ctx.arc(x + w - r, y + r, r, 1.5 * Math.PI, 2 * Math.PI)
      ctx.lineTo(x + w, y + h - r)
      ctx.lineTo(x + w - r, y + h)
      // 右下角
      ctx.arc(x + w - r, y + h - r, r, 0, 0.5 * Math.PI);
      ctx.lineTo(x + r, y + h)
      ctx.lineTo(x, y + h - r)
      // 左下角
      ctx.arc(x + r, y + h - r, r, 0.5 * Math.PI, Math.PI)
      ctx.lineTo(x, y + r)
      ctx.lineTo(x + r, y)
      ctx.fillStyle = color
      ctx.fill()
      ctx.closePath()
    },
    // 文字自动换行
    wordsWrap (ctx, name, nameWidth, maxWidth, startX, srartY, wordsHight) {
      let lineWidth = 0
      let lastSubStrIndex = 0
      for (let i = 0; i < name.length; i++) {
        lineWidth += ctx.measureText(name[i]).width
        if (lineWidth > maxWidth) {
          ctx.fillText(name.substring(lastSubStrIndex, i), startX, srartY)
          srartY += wordsHight
          lineWidth = 0
          lastSubStrIndex = i
        }
        if (i === name.length - 1) {
          ctx.fillText(name.substring(lastSubStrIndex, i + 1), startX, srartY)
        }
      }
    },
    // 绘制远程网络图片
    async drawImg (url, ctx, startX, startY, width, height) {
      let _this = this
      return new Promise(resolve => {
        exec()
        async function exec () {
          wx.getImageInfo({
            src: url,
            success: function (res) {
              const filePath = res.path
              ctx.drawImage(filePath, startX, startY, width, height)
              resolve()
            },
            fail: function (err) {
              console.log(err)
            },
            complete: function (err) {
              console.log(err)
            }
          })
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.share_layout_box {
  position: fixed;
  left: -1000px;
  top: -1000px;
  // z-index: 999;
}
</style>